package com.vilinno.tlias.controller;

import com.vilinno.tlias.pojo.Dept;
import com.vilinno.tlias.pojo.Result;
import com.vilinno.tlias.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/depts")
@RestController
public class DeptController {

    private static final Logger log = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

//    @RequestMapping(value="/depts", method=RequestMethod.GET)
    @GetMapping
    public Result list(){

        log.info("查询部门数据");
//        System.out.println("查询部门数据");
        List<Dept> deptList=deptService.findAll();

        return Result.success(deptList);

    }

//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request){
//        String id=request.getParameter("id");
//        Integer deptId=Integer.parseInt(id);
//        System.out.println("删除部门序号为： "+id);
//        deptService.delete(deptId);
//        return Result.success();
//    }

    @DeleteMapping
    public Result delete(@RequestParam("id") Integer id){

        log.info("删除部门序号为:{}",id);
//        System.out.println("删除部门序号为： "+id);
        try{
            deptService.deleteById(id);
        }catch(Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

    @PostMapping
    public Result add(@RequestBody Dept dept){
        log.info("添加的新部门名称为：{}",dept);
//        System.out.println("添加的新部门名称为： "+dept);
        try{
            deptService.add(dept);
        }catch(Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") Integer deptId) {
        log.info("查询的部门序号为：{}",deptId);
//        System.out.println("查询的部门序号为： " + deptId);
        Dept dept;
        try {
            dept = deptService.getById(deptId);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(dept);
    }

    @PutMapping
    public Result update(@RequestBody Dept dept){
        log.info("修改的部门为：{}",dept);
//        System.out.println("修改的部门为： " + dept);
        try {
            deptService.update(dept);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success();
    }
}
